<?php

/**
 * Apache、Nginx、PHP Server
 */

if (!isset($_SERVER["REQUEST_URI"]) || isset($argv)) return;

define('ROOT_PATH', dirname(__DIR__) . DIRECTORY_SEPARATOR);

require ROOT_PATH . 'vendor/autoload.php';
include ROOT_PATH . 'app/route/web.php';

$uri = str_replace('/index.php', '', $_SERVER["REQUEST_URI"]);
$path = strstr($uri, '?', true) ?: $uri;
$path = ltrim($path, '/');

function response($code, $data, $headers = []) {
    if (is_array($data) || is_object($data)) {
        $data = json_string($data, 1);
        header('Content-Type: application/json; charset=utf-8');
    } else {
        $data = (string) $data;
    }
    header('Content-Length: '. strlen($data));
    echo $data;
}

if (!$path) {
    response(404, ["code" => 1, "message"=> "index ok"]);
    return;
}

if (!isset($routes[$path])) {
    response(404, ["code" => 404, "message"=> "Not Found"]);
    return;
}

$params = $_GET;
$route = $routes[$path];

try {
    $request = null;
    $data = call_user_func([new $route[0]($request), $route[1]], $params);
    response(200, $data);
}
catch (\Throwable $e) {
    $data = json_string(filter_err($e, 1), 1);
    $data = '<pre>'. PHP_EOL. $data;
    response(500, $data);
}
